package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //判断
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     * @param employeeDTO
     * @return
     */

    @Override
    public Result add(EmployeeDTO employeeDTO) {
        //判断非空
        if (employeeDTO == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //判断用户名是否存在
        Employee byUsername = employeeMapper.getByUsername(employeeDTO.getUsername());
        if (byUsername != null) {
            return Result.error(MessageConstant.USER_ALREADY_EXISTS);
        }

        Employee employee = new Employee();
        //对象的属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);
        //设置状态码
        employee.setStatus(StatusConstant.ENABLE);
        //对密码加密储存
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //设置当前记录的创建时间和修改时间
        // employee.setCreateTime(LocalDateTime.now());
        // employee.setUpdateTime(LocalDateTime.now());
        // //设置创建人的id和修改人的id
        // employee.setCreateUser(BaseContext.getCurrentId());
        // employee.setUpdateUser(BaseContext.getCurrentId());
        //调用mapper接口
        employeeMapper.add(employee);
        return Result.success();
    }

    /**
     * 分页查询
     * @param dto
     * @return
     */

    @Override
    public Result page(EmployeePageQueryDTO dto) {
        //非空判断
        if (dto.getPage()==null){
            //如果为空,设置默认值
            dto.setPage(1);

        }
        if (dto.getPageSize()==null){
            dto.setPageSize(10);
        }
        //开启分页查询
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        //调用mapper方法
      Page<Employee> employees= employeeMapper.page(dto);
        //封装数据
        PageResult pageResult = new PageResult();
        pageResult.setTotal(employees.getTotal());
        pageResult.setRecords(employees.getResult());

        //返回
        return Result.success(pageResult);
    }

    /**
     * 启用和禁用
     *
     * @param status
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Result updateStatus(Integer status, Long id) {

        //调用mapper方法,设置状态
        Employee employee=new Employee();
        employee.setStatus(status);
        employee.setId(id);
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.updateEmp(employee);
        //返回
        return Result.success();
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public Result selectById(Long id) {
        //非空判断
        if (id==null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //调用mapper
      Employee employee= employeeMapper.selectById(id);
        //密码隐藏,安全
        employee.setPassword("*******");
        //返回查询的数据
        return Result.success(employee);
    }

    /**
     * 修改员工
     *
     * @param dto
     * @return
     */
    @Override
    public Result updateEmp(EmployeeDTO dto) {
        //非空判断
        if (dto.getId()==null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //调用mapper方法
        Employee employee=new Employee();
        //拷贝文件
        BeanUtils.copyProperties(dto,employee);
        // employee.setUpdateTime(LocalDateTime.now());
        // employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.updateEmp(employee);

        return Result.success();
    }

}
